package com.gl.portal.system.service;

import com.gl.common.exception.CustomException;
import com.gl.common.util.StringUtils;
import com.gl.portal.system.entity.SysArea;
import com.gl.portal.system.repository.SysAreaRepository;
import com.gl.portal.system.vo.SysAreaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 */
@Service
public class SysAreaService {

    @Autowired
    private SysAreaRepository areaRepository;


    public List<SysAreaVo> list(SysAreaVo vo) {
        return areaRepository.findAll((root, query, cb) -> {
            Predicate predicate = cb.and();

            List<Predicate> list = new ArrayList<>();
            list.add(cb.equal(root.get("parentId"), vo.getParentId() == null ? 0 : vo.getParentId()));
            if (vo != null) {
                if (StringUtils.isNotBlank(vo.getName())) {
                    predicate = cb.and(predicate, cb.like(root.get("name"), "%" + vo.getName() + "%"));
                    list.add(predicate);
                }
            }
            return cb.and(list.toArray(new Predicate[list.size()]));
            //return predicate;
        }, Sort.by("sortby")).stream().map(this::convert).collect(Collectors.toList());
    }

    /**
     * 数据转换
     *
     * @param entity 菜单实体
     * @return 菜单VO
     */
    private SysAreaVo convert(SysArea entity) {
        BeanCopier beanCopier = BeanCopier.create(SysArea.class, SysAreaVo.class, false);
        SysAreaVo vo = new SysAreaVo();
        beanCopier.copy(entity, vo, null);
        return vo;
    }

    public SysAreaVo findById(Long id) {
        Optional<SysArea> entity = areaRepository.findById(id);

        SysAreaVo vo = new SysAreaVo();
        BeanCopier beanCopier = BeanCopier.create(SysArea.class, SysAreaVo.class, false);
        beanCopier.copy(entity.get(), vo, null);
        return vo;
    }

    /**
     * 新增
     *
     * @param vo
     */
    public void save(SysAreaVo vo) {
        BeanCopier beanCopier = BeanCopier.create(SysAreaVo.class, SysArea.class, false);
        SysArea entity = new SysArea();
        beanCopier.copy(vo, entity, null);

        List<SysArea> sysArea = areaRepository.findByParentIdAndName(vo.getParentId(), vo.getName());
        if (sysArea.size() > 0) {
            throw new CustomException("行政区域数据已存在");
        }

        Optional<SysArea> optional = areaRepository.findById(vo.getParentId());
        if (!optional.isPresent()) {
            entity.setLevel(1);   //父id为0，为一级
        } else {
            SysArea parentSysArea = optional.get();
            entity.setLevel(parentSysArea.getLevel() + 1);
        }

        areaRepository.save(entity);
    }

    /**
     * 更新
     *
     * @param vo
     */
    public void update(SysAreaVo vo) {
        Optional<SysArea> optional = areaRepository.findById(vo.getId());
        if (!optional.isPresent()) {
            throw new CustomException("行政区域数据不存在");
        }
        SysArea existArea = optional.get();

        if (vo.getParentId().longValue() != existArea.getParentId() || !vo.getName().equals(existArea.getName())) {
            List<SysArea> sysArea = areaRepository.findByParentIdAndName(vo.getParentId(), vo.getName());
            if (sysArea.size() > 0) {
                throw new CustomException("行政区域数据已存在");
            }
        }

        SysArea entity = new SysArea();
        BeanCopier beanCopier = BeanCopier.create(SysAreaVo.class, SysArea.class, false);
        beanCopier.copy(vo, entity, null);

        if (entity.getParentId().longValue() == 0) {
            entity.setLevel(1);
        } else {
            SysArea parentSysArea = areaRepository.findById(entity.getParentId()).get();
            entity.setLevel(parentSysArea.getLevel() + 1);
        }

        areaRepository.save(entity);
    }

    /**
     * 删除信息
     *
     * @param id
     */
    public void delete(Long id) {

        Integer count = areaRepository.countByParentId(id);
        if (count > 0) {
            throw new CustomException("有子节点数据，不允许删除");
        }
        areaRepository.deleteById(id);
    }

}
